package com.example.service.impl;

import com.example.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service("fileServiceImpl")
public class FileServiceImpl implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    
    @Value("${file.upload.dir:./uploads}")
    private String uploadDir;
    
    @Override
    public String upload(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        
        try {
            // 确保目录存在
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID() + extension;
            
            // 保存文件
            Path filePath = uploadPath.resolve(filename);
            Files.copy(file.getInputStream(), filePath);
            
            // 返回访问URL
            return "/uploads/" + filename;
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            return null;
        }
    }
    
    @Override
    public boolean deleteFile(String objectName) {
        if (objectName == null || objectName.isEmpty()) {
            return false;
        }
        
        try {
            // 从路径中提取文件名
            String filename = objectName;
            if (objectName.startsWith("/uploads/")) {
                filename = objectName.substring("/uploads/".length());
            }
            
            Path filePath = Paths.get(uploadDir, filename);
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            logger.error("文件删除失败", e);
            return false;
        }
    }
} 